#include "rtsp_packet_parser.h"
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <QRegExp>
#include <QString>
#include <QDebug>
#include <QDataStream>

using namespace std;
using namespace rtsp;

RTSPPacketParser::RTSPPacketParser()
{
}

RTSPPort RTSPPacketParser::GetClientPort(const char *in)
{
    RTSPPort rtsp_port;
    int i = 0;
    int rtsp_port_idx = 0;
    while(memcmp(in + i, "\r\n\r\n", 4) != 0)
    {
        if(memcmp(in + i, "client_port=", 12) == 0 && rtsp_port_idx == 0)
        {
            rtsp_port_idx = i + 12;
        }
        if(memcmp(in + i, "-", 1) == 0 && rtsp_port_idx != 0)
        {
            char rtp_port_ch[6] = {0};
            memcpy(rtp_port_ch, in + rtsp_port_idx, i - rtsp_port_idx);
            rtsp_port.rtp_port = atoi(rtp_port_ch);
            rtsp_port.rtcp_port = rtsp_port.rtp_port + 1;
            return rtsp_port;
        }
        i++;
    }
    return rtsp_port;
}

void RTSPPacketParser::ReplaceClientPort(const char *in, char *out, RTSPPort ports)
{
    QString rep(QString("client_port=%1-%2").arg(ports.rtp_port).arg(ports.rtcp_port));
    QRegExp rx("client_port=(\\d+)-(\\d+)");
    QString ctx(in);
    ctx = ctx.replace(rx, rep);
    memcpy(out, ctx.toLocal8Bit(), ctx.size());
}

RTSPPort RTSPPacketParser::GetServerPort(const char *in)
{
    RTSPPort rtsp_port;
    int i = 0;
    int rtsp_port_idx = 0;
    while(memcmp(in + i, "\r\n\r\n", 4) != 0)
    {
        if(memcmp(in + i, "server_port=", 12) == 0 && rtsp_port_idx == 0)
        {
            rtsp_port_idx = i + 12;
        }
        if(memcmp(in + i, "-", 1) == 0 && rtsp_port_idx != 0)
        {
            char rtp_port_ch[6] = {0};
            memcpy(rtp_port_ch, in + rtsp_port_idx, i - rtsp_port_idx);
            rtsp_port.rtp_port = atoi(rtp_port_ch);
            rtsp_port.rtcp_port = rtsp_port.rtp_port + 1;
            return rtsp_port;
        }
        i++;
    }
    return rtsp_port;
}

void RTSPPacketParser::ReplaceServerPort(const char *in, char *out, RTSPPort ports)
{
    QString rep(QString("server_port=%1-%2").arg(ports.rtp_port).arg(ports.rtcp_port));
    QRegExp rx("server_port=(\\d+)-(\\d+)");
    QString ctx(in);
    ctx = ctx.replace(rx, rep);
    memcpy(out, ctx.toLocal8Bit(), ctx.size());
}
